/*
 invite.go
 Created by hupfei on 2019-07-02
*/

package v1

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/app/middleware"
	"zimuzu_cvn_web_api/service"
)

type InviteAPI struct {
}

func (a InviteAPI) Name() string {
	return "invite API"
}

func (a InviteAPI) Bind() {
	authAPI := config.C.Router.Group("/v1/app", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		authAPI.GET("inviteInfo", inviteInfo)
	}
	API := config.C.Router.Group("/v1/app", middleware.TrackLog())
	{
		API.GET("acceptInvite", acceptInvite)
	}
}

/*
 * @ Author: hupfei
 * @ Description: 推荐好友
 **/
func inviteInfo(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	res, err := service.InviteInfo(uid)
	if err != nil {
		api.SendResponse(c, errors.New("查询推荐好友信息失败"), nil)
		return
	}
	errno.OK.Info = "返回推荐好友信息成功"
	api.SendResponse(c, errno.OK, res)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 接受好友邀请
 **/
func acceptInvite(c *gin.Context) {
	var params model.AcceptInviteParams
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	//校验验证码
	var scene = service.SendCodeSceneInvite
	if params.Source == 1 {
		scene = service.SendCodeSuperNodeInvite
	}
	err = service.ValidateCode(params.Phone, scene, params.PhoneCode)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	//判断手机号是否已注册
	res, _ := service.CheckAccountReg(params.Phone, params.PhoneArea)
	if !res {
		//没有注册需要生成sign去下一步注册
		sign := service.CreateRegSign(params.Phone)
		re := map[string]string{
			"sign": sign,
		}
		errno.OK.Info = "请先注册"
		api.SendResponse(c, errno.OK, re)
		return
	}

	//查询uid
	user, _ := model.GetUserByMobile(config.C.DB.DB, params.Phone, params.PhoneArea)
	re, info, err := service.FillInInviteCode(user.Uid, params)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	errno.OK.Info = info
	api.SendResponse(c, errno.OK, re)
	return
}